package com.woniu.controller.config.upload;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    //上传到指定的服务器地址，地址从yaml文件中读取
    @Value("${upload.path}")
    private String uploadPath;

    /**
     * 上传文件
     * 1. 必须是POST请求
     * 2. 返回上传成功的文件名，文件名是随机生成的
     * 3. 形参名字必须与客户端提交的name名字一样
     */
    @PostMapping("/upload")
    public ResponseEntity<String> upload(MultipartFile file) throws IOException {
        //1获取原来名字
        String originalFilename = file.getOriginalFilename();
        //2将文件名改为名成唯一标识符字符串
        //得到原来文件名的后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //得到主文件名 e00dec1a-febe-11ed-bfa9-9c2dcd7a053a
        String newFileName = UUID.randomUUID().toString() + suffix;
        //上传路径
        String fileName = uploadPath + newFileName;
        //上传文件
        file.transferTo(new File(fileName));
        System.out.println("上传成功：" + fileName);
        //4返回新文件名
        return ResponseEntity.ok(newFileName);
    }
}
